﻿using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Linq.Extensions;
using Abp.MultiTenancy;
using Abp.Runtime.Security;
using Partner.Surround.Authorization;
using Partner.Surround.Authorization.Roles;
using Partner.Surround.Authorization.Users;
using Partner.Surround.Editions;
using Partner.Surround.MultiTenancy.Dto;
using Microsoft.AspNetCore.Identity;
using Abp.UI;

namespace Partner.Surround.MultiTenancy
{
    /// <summary>
    /// 租户应用服务
    /// </summary>
    public class TenantAppService : SurroundAppServiceBase, ITenantAppService
    {
        #region 初始化
        private readonly IRepository<Tenant, int> _tenantRepository;
        private readonly TenantManager _tenantManager;
        public TenantAppService(IRepository<Tenant, int> tenantRepository,
            TenantManager tenantManager)
        {
            _tenantRepository = tenantRepository;
            _tenantManager = tenantManager;
        }
        #endregion

        public async Task<TenantListDto> GetTenant(EntityDto<int> input)
        {
            var tenant = await _tenantRepository.GetAsync(input.Id);

            return ObjectMapper.Map<TenantListDto>(tenant);
        }

        public async Task<ListResultDto<TenantListDto>> GetTenantsList()
        {
            var tenants = await _tenantRepository.GetAllListAsync();

            return new ListResultDto<TenantListDto>(
                tenants.Select(item =>
                {
                    var dto = ObjectMapper.Map<TenantListDto>(item);
                    return dto;
                }).ToList());
        }

        [AbpAuthorize(PermissionNames.Pages_Frame_Tenants_MoveTenantToAnotherEdition)]
        public async Task MoveTenantToAnotherEdition(MoveTenantToAnotherEditionInput input)
        {
            if (input.SourceEditionId == input.TargetEditionId)
            {
                throw new UserFriendlyException("原版本与目标版本一致，无需切换");
            }

            var tenant = await _tenantManager.GetByIdAsync(input.TenantId);
            tenant.EditionId = input.TargetEditionId;
            await _tenantManager.UpdateAsync(tenant);
        }
    }
}

